/**
 * Copyright 2008-2009 HAN.BIFANG
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package han.bifang.gwt.client.service.content;

import han.bifang.gwt.client.common.Content;
import han.bifang.gwt.client.common.GwtContext;
import han.bifang.gwt.client.common.KeyNamePairs;
import han.bifang.gwt.client.common.RequestObject;
import han.bifang.gwt.client.common.ResponseObject;
import han.bifang.gwt.client.common.entity.MappingService;
import han.bifang.gwt.client.common.util.StringUtils;
import han.bifang.gwt.client.communicate.BifangGWTServiceAsync;
import han.bifang.gwt.client.service.ServiceContentConstants;
import han.bifang.gwt.client.service.ServiceMessages;

import java.util.ArrayList;
import java.util.HashMap;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.HTMLTable.CellFormatter;
import com.google.gwt.user.client.ui.HTMLTable.ColumnFormatter;

/**
 * 
 * @Author Kent
 */
public class MappingServiceRootContent1 extends Content {

	private BifangGWTServiceAsync service = null;

	private GwtContext context = null;

	private ServiceMessages cons;

	private VerticalPanel panel = null;

	private TextBox code, version;
	private TextArea desc;
	private ListBox bus;

	private String id;

	private String domainId;

	private MappingService s;
	
	private FlexTable vt;

	private AsyncCallback<ResponseObject> cb = new AsyncCallback<ResponseObject>() {
		public void onSuccess(ResponseObject res) {
			String code1 = res.getCode();
			if (!code1.equals("0")) {
				Window.alert("There was an error: " + res.getMsg());
				return;
			}
			ArrayList ret = (ArrayList) res.getResponse();
			s = (MappingService) ret.get(0);
			ArrayList<String> busRef = (ArrayList<String>) ret.get(1);
			HashMap tmp = new HashMap();
			for (String id : busRef) {
				tmp.put(id, id);
			}

			ArrayList v = (ArrayList) ret.get(2);

			Grid table = new Grid(5, 2);
			table.setCellPadding(1);
			table.setCellSpacing(1);
			table.setBorderWidth(1);

			ColumnFormatter cf = table.getColumnFormatter();
			cf.setWidth(0, "15%");
			cf.setWidth(1, "55%");

			CellFormatter ff = table.getCellFormatter();
			ff.setStyleName(0, 0, "tablecol");
			ff.setStyleName(1, 0, "tablecol");
			ff.setStyleName(2, 0, "tablecol");
			ff.setStyleName(3, 0, "tablecol");
			ff.setStyleName(4, 0, "tablecol");

			table.setHTML(0, 0, cons.name());
			table.setHTML(1, 0, cons.remoteCode());
			table.setHTML(2, 0, cons.localCode());
			table.setHTML(3, 0, cons.chooseBus());
			table.setHTML(4, 0, cons.desc());

			code = new TextBox();
			code.setVisibleLength(32);

			bus = new ListBox(true);

			desc = new TextArea();
			desc.setCharacterWidth(64);
			desc.setVisibleLines(6);

			table.setHTML(0, 1, s.getName());
			table.setHTML(1, 1, s.getRemoteCode());

			table.setWidget(2, 1, code);
			code.setText(s.getLocalCode());

			table.setWidget(3, 1, bus);

			table.setWidget(4, 1, desc);
			desc.setText(s.getDescription());

			ArrayList<KeyNamePairs> l = (ArrayList<KeyNamePairs>) ret.get(3);

			bus.setVisibleItemCount(l.size() == 0 ? 1 : l.size());
			int ii = 0;
			for (KeyNamePairs k : l) {
				bus.addItem(k.getName(), k.getId());
				if (tmp.get(k.getId()) != null) {
					bus.setSelectedIndex(ii);
				}
				ii++;

			}
			
			HorizontalPanel hh = new HorizontalPanel();
			Button b = new Button(cons.modify());
			b.addClickListener(new ClickListener() {
				public void onClick(Widget send) {
					if (!validate())
						return;

					s.setDescription(desc.getText());
					s.setLocalCode(code.getText());

					ArrayList<String> busR = new ArrayList<String>();
					for (int i = 0, j = bus.getItemCount(); i < j; i++) {
						if (bus.isItemSelected(i)) {
							busR.add(bus.getValue(i));
						}
					}
					ArrayList<Object> re = new ArrayList<Object>();
					re.add(s);
					re.add(busR);
					RequestObject req = new RequestObject();
					req
							.setAction("han.bifang.gwt.server.action.service.ModifyMappingServiceAction");
					req.setRequest(re);
					service.call(req, modifycb);

				}
			});
			hh.add(b);
			hh.add(new HTML("&nbsp;&nbsp;"));
			
			b = new Button(cons.remove());
			b.addClickListener(new ClickListener() {
				public void onClick(Widget send) {
					if (!validate())
						return;
					HashMap p = new HashMap();
					p.put("s", s);
					listener.onContentChanged(ServiceContentConstants.REMOTE_SERVICE_ROOT, 
							ServiceContentConstants.REMOVE_REMOTE_SERVICE, p);

				}
			});
			hh.add(b);
			
			panel.add(table);
			panel.add(hh);
			panel.add(new HTML("&nbsp;"));
			panel.add(new HTML("&nbsp;"));

			HorizontalPanel h = new HorizontalPanel();
			version = new TextBox();
			version.setVisibleLength(20);

			h.add(version);
			Button b1 = new Button(cons.importVersion());
			b1.addClickListener(new ClickListener() {
				public void onClick(Widget sender) {
					if (!validate1())
						return;
					ArrayList l = new ArrayList();

					l.add(id);
					l.add(s.getLocalCode());
					l.add(version.getText());
					RequestObject req = new RequestObject();
					req.setAction("han.bifang.gwt.server.action.service.CreateMappingVersionAction");
					req.setRequest(l);
					service.call(req, cb1);

				}
			});
			h.add(new HTML("&nbsp;&nbsp;"));
			h.add(b1);
			panel.add(h);

			vt = new FlexTable();
			vt.setBorderWidth(1);
			vt.setCellPadding(1);
			vt.setCellSpacing(1);
			
			cf = vt.getColumnFormatter();
			cf.setWidth(0, "30%");
			cf.setWidth(1, "15%");

			ff = vt.getCellFormatter();
			ff.setStyleName(0, 0, "tablecol");
			ff.setStyleName(0, 1, "tablecol");

			vt.setHTML(0, 0, cons.version());
			vt.setHTML(0, 1, "&nbsp;");

			for (int i = 0, j = v.size(); i < j; i++) {
				int n = vt.getRowCount();
				vt.insertRow(n);
				vt.setHTML(n, 0, (String) v.get(i));
				Button bb = new Button(cons.remove());
				RemoveVersionListener ll = new RemoveVersionListener();
				ll.setVersion((String) v.get(i));
				ll.setId(id);
				ll.setRow(n);
				ll.setTable(vt);
				ll.setService(service);
				bb.addClickListener(ll);
				vt.setWidget(n, 1, bb);
			}
			panel.add(vt);
		}

		public void onFailure(Throwable caught) {
			Window.alert("There was an error: " + caught.toString());
		}
	};

	private AsyncCallback<ResponseObject> cb1 = new AsyncCallback<ResponseObject>() {
		public void onSuccess(ResponseObject res) {
			String code = res.getCode();
			if (! code.equals("0")) {
				Window.alert("There was an error: " + res.getMsg());
				return;
			}
			int r = vt.getRowCount();
			vt.insertRow(r);
			vt.setHTML(r, 0, version.getText());
			
			Button bb = new Button(cons.remove());
			RemoveVersionListener ll = new RemoveVersionListener();
			ll.setVersion(version.getText());
			ll.setId(id);
			ll.setRow(r);
			ll.setTable(vt);
			ll.setService(service);
			bb.addClickListener(ll);
			
			version.setText("");
			
			vt.setWidget(r, 1, bb);
			
		}

		public void onFailure(Throwable caught) {
			Window.alert("There was an error: " + caught.toString());
		}
	};
	
	private AsyncCallback<ResponseObject> modifycb = new AsyncCallback<ResponseObject>() {
		public void onSuccess(ResponseObject res) {
			String code = res.getCode();
			if (! code.equals("0")) {
				Window.alert("There was an error: " + res.getMsg());
				return;
			}
			Window.alert(cons.modifyOK());
			
		}

		public void onFailure(Throwable caught) {
			Window.alert("There was an error: " + caught.toString());
		}
	};

	public MappingServiceRootContent1(ServiceMessages cons,
			BifangGWTServiceAsync service, GwtContext context, String id,
			String domainId) {
		this.cons = cons;
		this.service = service;
		this.context = context;
		this.id = id;
		this.domainId = domainId;

		panel = new VerticalPanel();
		panel.setSpacing(5);
		panel.setWidth("100%");

		initWidget(panel);

	}

	public void onLoad() {
		HTML h = new HTML(cons.serviceBasicInfo());
		panel.add(h);

		RequestObject req = new RequestObject();
		req
				.setAction("han.bifang.gwt.server.action.service.GetRemoteServiceDetailAction");
		ArrayList ids = new ArrayList();
		ids.add(id);
		ids.add(domainId);
		req.setRequest(ids);
		service.call(req, cb);
	}

	private boolean validate() {

		if (!StringUtils.checkLenght(desc.getText(), 1, 1024)) {
			Window.alert(cons.lengthError(cons.desc(), "1", "1024"));
			return false;

		}
		if (!StringUtils.checkLenght(code.getText(), 1, 32)) {
			Window.alert(cons.lengthError(cons.code(), "1", "32"));
			return false;

		}

		if (bus.getSelectedIndex() < 0) {
			Window.alert(cons.mustChooseBusError());
			return false;
		}

		return true;

	}

	private boolean validate1() {

		if (!StringUtils.checkLenght(version.getText(), 1, 20)) {
			Window.alert(cons.lengthError(cons.version(), "1", "20"));
			return false;

		}

		return true;

	}

	private static class RemoveVersionListener implements ClickListener {

		private String version;
		private String id;
		private BifangGWTServiceAsync service;
		private FlexTable table;
		private int row;

		public void setRow(int i) {
			row = i;
		}

		private AsyncCallback<ResponseObject> cb = new AsyncCallback<ResponseObject>() {
			public void onSuccess(ResponseObject res) {
				String code1 = res.getCode();
				if (!code1.equals("0")) {
					Window.alert("There was an error: " + res.getMsg());
					return;
				}

				table.removeRow(row);

			}

			public void onFailure(Throwable caught) {
				Window.alert("There was an error: " + caught.toString());
			}
		};

		public void setTable(FlexTable table) {
			this.table = table;
		}

		public void setService(BifangGWTServiceAsync service) {
			this.service = service;
		}

		public void setId(String id) {
			this.id = id;
		}

		public void setVersion(String version) {
			this.version = version;
		}

		public void onClick(Widget sender) {
			ArrayList<String> l = new ArrayList<String>();
			l.add(id);
			l.add(version);
			RequestObject req = new RequestObject();
			req
					.setAction("han.bifang.gwt.server.action.service.RemoveMappingVersionAction");
			req.setRequest(l);
			service.call(req, cb);
		}

	}

}
